

var oschat = {
	uid:""
};

global.eventArray = new Array();

oschat.main=(function(){
	return {
		init:function(){
			oschat.uid = util.getQuery("uid");
			im.api.initMainWs(oschat.uid);

			im.ws.onopen = function() { 
				console.info("ws access");
	        };

	        // 关闭WebSocket的回调
			im.ws.onclose = function() {
			};

			// 收到服务器发送的文本消息, event.data表示文本内容
			im.ws.onmessage = function(e) { 
				console.log(e.data);
				var msg = eval('(' + e.data + ')');
				if(msg.kind=="EVENT"){
					var event = msg.result;
					if(event.event=="REFRESH_ONLINE_USERS" || event.event=="LOGIN"){
						oschat.main.onlineUserBind(event);
					}else if(event.event=="CLOSE"){
						oschat.main.offlineUserBind(event);
					}else if(event.event == "NEW_SESSION"){
						oschat.main.newSessionBind(event);
					}
				}
			};
		},
		
		startChatEvent:function(u){
			$('#olu-'+u.id).dblclick(function(){
				console.info('start chat with '+ u.id);
				window.frames["chatFrame"].chatmain.win.addChat(u);
			});
		},
		
		onlineUserBind : function(event){
			var u = event.u;
			if(u.id == oschat.uid){
				$('.user-name').html(u.name);
				$('.user-resume').html(u.resume);
				$('.user-photo img').attr("src",u.portrait);
			}else{
				/**
					<div class="u">
								<div class="u-photo">
									<img alt="u" width="36" height="36"
										src="http://static.oschina.net/uploads/user/124/249315_100.jpg?t=1366073366000">
								</div>
								<div class="u-info">
									<div class="u-name">铂金小猪</div>
									<div class="u-resume">大地瓜</div>
								</div>
							</div>
				*/
				var id = u.id;
				var name = u.name;
				var portrait = u.portrait=="null" ? "" : u.portrait;
				var resume = u.resume==null ?"":u.resume;
				var html = '<div class="u" id="olu-'+id+'"><div class="u-photo"><img alt="u" width="36" height="36" src="'+portrait+'"></div><div class="u-info"><div class="u-name">'+name+'</div><div class="u-resume">'+resume+'</div></div></div>';
				$('.u-list').append(html);
				var onlinecount = $('#onlinecount').html();
				$('#onlinecount').html(parseInt(onlinecount==""?0:onlinecount)+1);
				oschat.main.startChatEvent(u);
			}
		},
		offlineUserBind:function(event){
			var u = event.u;
			$('#olu-'+u.id).remove();
		},
		newSessionBind:function(event){
			global.eventArray.push(event);
			window.open('notice.html?e='+global.eventArray.length, '_blank', 'screenX='+(screen.width-170)+',screenY='+(screen.height-120)+',width=150,height=100');
		},

		chatWith:function(u){
			window.frames["chatFrame"].chatmain.win.addChat(u);
			//nw.win.show();
		}
	};
})();

document.onselectstart = function() {
	return false;
};

